package thread.ch04;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import thread.annotation.ThreadSafe;

/**
 * Point类是不可变的，因而是线程安全的。程序可以自由地共享与发布不可变值。
 * <p />
 * DelegatingVehicleTracker没有使用任何显示的同步；ConcurrentMap管理了所有对状态的访问，而且Map的键与值都是不可变的。
 * 
 * @author Edgar Zhang
 * 
 */
@ThreadSafe
public class DelegatingVehicleTracker {

	private final ConcurrentMap<String, Point> locations;
	private final Map<String, Point> unmodifiabledMap;

	public DelegatingVehicleTracker(ConcurrentMap<String, Point> points) {
		this.locations = new ConcurrentHashMap<String, Point>(points);
		this.unmodifiabledMap = Collections.unmodifiableMap(locations);
	}

	public Map<String, Point> getLocations() {
		return unmodifiabledMap;
	}

	public Point getLocation(String key) {
		return locations.get(key);
	}

	public void setLocation(String id, int x, int y) {
		if (locations.replace(id, new Point(x, y)) == null)
			throw new IllegalArgumentException("invalid vehicle name: " + id);
	}

	// Alternate version of getLocations (Listing 4.8)
	public Map<String, Point> getLocationsAsStatic() {
		return Collections
				.unmodifiableMap(new HashMap<String, Point>(locations));
	}
}
